package com.ftg.supermarket.service;

import com.ftg.supermarket.comm.PageEx;
import com.ftg.supermarket.comm.ToPage;
import com.ftg.supermarket.dto.GoodsDto;
import com.ftg.supermarket.mapper.GoodsMapper;
import com.ftg.supermarket.util.MapperUtil;
import com.ftg.supermarket.vo.GoodsListVo;

import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * 商品业务
 *
 * @author 布衣
 */
public class GoodsService {

    GoodsMapper goodsMapper;
    MapperUtil mapperUtil = new MapperUtil("config/configuration.xml");

    public GoodsService() throws IOException {
        goodsMapper = mapperUtil.getMapper(GoodsMapper.class);
    }

    public ToPage<PageEx<GoodsListVo>> goodsList(GoodsDto goodsDto) {
        PageEx<GoodsListVo> pageEx = new PageEx<>();
        pageEx.setPageNum(goodsDto.getStart());
        pageEx.setPageSize(goodsDto.getSize());
        pageEx.setRows(goodsMapper.goodsList(goodsDto));
        pageEx.setTotal(goodsMapper.countList(goodsDto));
        return ToPage.success("获取商品列表成功", pageEx);
    }

    public ToPage<String> deleteGoodsByIds(List<Integer> ids) {
        try {
            goodsMapper.backPicture(ids);
            goodsMapper.deletePictureByIds(ids);
            goodsMapper.deleteGoodsPictureByIds(ids);
            goodsMapper.deleteGoodsByIds(ids);
            mapperUtil.myCommit();
        } catch (Exception e) {
            mapperUtil.myRollback();
            return ToPage.error("删除失败");
        } finally {
            mapperUtil.myClose();
        }
        return ToPage.success("删除成功", null);
    }

    public static void main(String[] args) throws IOException {
        GoodsService goodsService = new GoodsService();
        goodsService.deleteGoodsByIds(Arrays.asList(1,2));
    }

}
